package com.gitee.jmash.websocket.service;

import com.gitee.jmash.common.lock.DistributedLock;
import com.gitee.jmash.core.jaxrs.ParamsValidationException;
import com.gitee.jmash.websocket.endpoint.SubscribeHandle;
import com.gitee.jmash.websocket.mapper.MessageMapper;
import com.gitee.jmash.websocket.model.AiChatMessage;
import com.gitee.jmash.websocket.model.Message;
import com.gitee.jmash.websocket.model.MsgType;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import jakarta.validation.Valid;
import jakarta.validation.executable.ValidateOnExecution;
import jmash.websocket.protobuf.AiChatMsgReq;
import jmash.websocket.protobuf.ChannelMsgReq;
import jmash.websocket.protobuf.ChannelUserMsgReq;

/**
 * 消息服务.
 *
 * @Author wyy
 * @Date 2025/7/16 18:05
 */
@ApplicationScoped
@ValidateOnExecution
public class MessageService {

  @Inject
  DistributedLock lock;

  /**
   * 给指定频道下发送消息.
   */
  public int sendChannelMsg(@Valid ChannelMsgReq req) {
    if (!lock.lock(req.getRequestId(), 60)) {
      throw new ParamsValidationException("requestId", "客户端发起重复请求");
    }
    Message message = new Message();
    message.setMsgType(MsgType.resp);
    message.setChannelId(req.getChannelId());
    message.setMessage(req.getMessage());
    return SubscribeHandle.sendMessage(message, req.getSync());
  }

  /**
   * 给指定频道下用户发送消息.
   */
  public boolean sendChannelUserMsg(@Valid ChannelUserMsgReq req) {
    if (!lock.lock(req.getRequestId(), 60)) {
      throw new ParamsValidationException("requestId", "客户端发起重复请求");
    }
    Message message = new Message();
    message.setMsgType(MsgType.resp);
    message.setChannelId(req.getChannelId());
    message.setMessage(req.getMessage());
    return SubscribeHandle.sendMessage(req.getUserId(), message, req.getSync());
  }

  /**
   * 发送AI聊天消息.
   */
  public boolean sendAIChatMsg(@Valid AiChatMsgReq req) {
    if (!lock.lock(req.getRequestId(), 60)) {
      throw new ParamsValidationException("requestId", "客户端发起重复请求");
    }
    AiChatMessage message = MessageMapper.INSTANCE.toAiChatMessage(req);
    return SubscribeHandle.sendMessage(req.getUserId(), message, req.getSync());
  }

}
